package com.ismartv.sale.control;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

public class UploadServlet extends HttpServlet{

	
	private String filePath="excelexporttest";    // 文件存放目录  
    private String tempPath = "excelexporttest_temp";    // 临时文件目录 
    
 // 初始化  
    public void init(ServletConfig config) throws ServletException  
    {  
        super.init(config);  
        // 从配置文件中获得初始化参数  
        filePath = config.getInitParameter("filepath");  
        tempPath = config.getInitParameter("temppath");  
        ServletContext context = getServletContext();  
        filePath = context.getRealPath(filePath);  
        tempPath = context.getRealPath(tempPath);  
        System.out.println("文件存放目录、临时文件目录准备完毕 ...");
        if(filePath == null)
        	filePath ="excelexporttest";
        if(tempPath == null)
        	tempPath ="excelexporttest_temp";
    }  
    
    
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		    response.setContentType("text/plain;charset=gbk");  
	        PrintWriter pw = response.getWriter();
	        try{
	            DiskFileItemFactory diskFactory = new DiskFileItemFactory();  
	            diskFactory.setSizeThreshold(4 * 1024);  
	            diskFactory.setRepository(new File(tempPath));
	            ServletFileUpload upload = new ServletFileUpload(diskFactory);  
	            upload.setSizeMax(4 * 1024 * 1024);  
	            List<FileItem> fileItems = upload.parseRequest(request);  
	            Iterator<FileItem> iter = fileItems.iterator();
	            while(iter.hasNext())  
	            {
	                FileItem item = (FileItem)iter.next();  
	                if(item.isFormField())  
	                {
	                    System.out.println("处理表单内容 ...");  
	                    processFormField(item, pw);  
	                }else{  
	                    System.out.println("处理上传的文件 ...");  
	                    processUploadFile(item, pw);  
	                }  
	            }
	            pw.close();  
	        }catch(Exception e){  
	            System.out.println("使用 fileupload 包时发生异常 ...");  
	            e.printStackTrace();  
	        }
	}

	
    private void processFormField(FileItem item, PrintWriter pw)  
        throws Exception  
    {  
        String name = item.getFieldName();  
        String value = item.getString();          
        pw.println(name + " : " + value + "\r\n");  
    }  
	

    private void processUploadFile(FileItem item, PrintWriter pw)  
        throws Exception  
    {  
        String filename = item.getName();         
        System.out.println("完整的文件名：" + filename);  
        int index = filename.lastIndexOf("\\");  
        filename = filename.substring(index + 1, filename.length());  
        long fileSize = item.getSize();  
        if("".equals(filename) && fileSize == 0)  
        {             
            System.out.println("文件名为空 ...");  
            return;  
        }
        File uploadFile = new File(filePath + "/" + filename);  
        item.write(uploadFile);  
        pw.println(filename + " 文件保存完毕 ...");  
        pw.println("文件大小为 ：" + fileSize + "\r\n");  
    }
    
    

}
